<template>
  <div class="son-page-container" :style="{ backgroundImage: `url(${website_bg_url})` }">
    <el-container class="main-container">
      <el-header height="10vh" class="header-container">
        <MyHeader />
      </el-header>

      <el-main>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="spacer">
              <div class="content-nav">
                <div class="nav-right">
                  <button class="nav-btn" @click="handleProductLibrary">
                    <el-icon class="btn-icon"><VideoCamera /></el-icon>
                    成品库
                  </button>
                </div>
              </div>
            </div>
            <div class="area-container menu-container area-container-sec">
              <div v-for="menu in menuList" :key="menu.id" class="menu-item">
                <div class="menu-title" @click="toggleSubMenu(menu)">
                  <span>{{ menu.name }}</span>
                  <i v-if="menu.children" :class="['arrow', menu.isOpen ? 'arrow-down' : 'arrow-right']"></i>
                </div>
                <div v-if="menu.children && menu.isOpen" class="sub-menu">
                  <div v-for="subMenu in menu.children"
                       :key="subMenu.id"
                       class="sub-menu-item"
                       :class="{ active: selectedSubMenu === subMenu.id }"
                       @click="selectSubMenu(subMenu)">
                    {{ subMenu.name }}
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="5">
            <div class="area-container center-area">
              <div class="center-content">
                <div class="center-top">
                  <div v-if="showDescriptionSection" class="input-section">
                    <div class="section-title">描述文字</div>
                    <textarea
                        v-model="description"
                        class="description-input"
                        placeholder="请输入描述文字..."
                        rows="4"
                    ></textarea>
                  </div>
                  <div v-if="showUploadSection" class="upload-section">
                    <div class="section-title">图片上传</div>
                    <div class="upload-mask-wrapper" style="position:relative;">
                      <template v-if="selectedImageData" >
                        <img :src="selectedImageData" alt="已上传图片" style="width:100%;border-radius:8px;object-fit:cover;cursor:pointer;" @click="handleCustomUploadClick" />
                      </template>
                      <template v-else>
                        <el-upload
                            class="upload-component"
                            drag
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            :disabled="true"
                        >
                          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                          <div class="el-upload__text">
                            将文件拖到此处，或<em>点击上传</em>
                          </div>
                          <template #tip>
                            <div class="el-upload__tip">
                              支持jpg/png文件
                            </div>
                          </template>
                        </el-upload>
                        <div class="overlay-upload-mask" @click="handleCustomUploadClick" style="position:absolute;inset:0;z-index:2;cursor:pointer;"></div>
                      </template>
                    </div>
                  </div>
                </div>

                <div class="center-bottom">
                  <div class="count-section">
                    <div class="section-content">
                      <div class="generate-content">
                        <!-- 第一行：生成个数 -->
                        <div class="generate-row">
                          <div class="row-label">生成个数</div>
                          <el-input-number
                              v-model="count"
                              :min="1"
                              :max="10"
                              class="count-input"
                              size="default"
                          />
                        </div>
                        <!-- 第二行：分辨率 -->
                        <div class="generate-row">
                          <div class="row-label">分辨率</div>
                          <el-select v-model="size" placeholder="请选择分辨率" class="size-select">
                            <el-option
                                v-for="item in sizeArr"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                          </el-select>
                        </div>
                        <!-- 第三行：按钮 -->
                        <div class="generate-row button-row">
                          <el-button
                              type="primary"
                              @click="handleGenerate"
                          >
                            立即生成
                          </el-button>
                          <el-button
                              type="warning"
                              @click="handleReset"
                              style="margin-left: 10px;"
                          >
                            清空内容
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="15">
            <div class="area-container right-area">
              <div class="right-content">
                <div class="right-header">
                  <div class="header-title">为您生成</div>
                  <div class="header-subtitle">AI生成，仅供参考，您对该内容的使用应严格遵循国家相关法律法规的规定</div>
                </div>
                <div class="right-main">
                  <!-- 内容展示区域 -->
                  <el-row :gutter="16" style="margin-top: 24px;">
                    <el-col v-for="(item, idx) in pictureContents" :key="idx" :span="6" style="margin-bottom: 16px;">
                      <DouyinShow :item="item" />
                    </el-col>
                  </el-row>
                </div>
                <div class="right-footer">
                  <el-button
                      type="primary"
                      @click="handlePublish"
                  >
                    授权发布
                  </el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <MyDialog
        v-model="showUploadDialog"
        title="素材上传"
        width="50%"
        :modal="true"
        :close-on-click-modal="false"
        @confirm="handleUploadConfirm"
    >
      <SourcePictureNew ref="sourcePictureNewRef" @confirm="handleUploadConfirm"/>
    </MyDialog>
    <!-- 任务名输入弹窗 -->
    <el-dialog
        v-model="showTaskNameDialog"
        title="请输入任务名"
        width="400px"
        :close-on-click-modal="false"
        align-center
    >
      <div>
        <el-input v-model="taskNameInput" placeholder="请输入任务名" />
      </div>
      <template #footer>
        <el-button @click="handleTaskNameCancel">取消</el-button>
        <el-button type="primary" @click="handleTaskNameConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 发布设置弹窗 -->
    <MyDialog
        v-model="showPublishDialog"
        title="发布设置"
        width="600px"
        :modal="true"
        :close-on-click-modal="false"
        @confirm="handlePublishConfirm"
        @cancel="handlePublishCancel"
    >
      <div class="publish-form">
        <!-- 发布类型 -->
        <div class="form-section">
          <div class="section-label">发布类型</div>
          <div class="publish-type-buttons">
            <button
                :class="['type-btn', publishForm.publishType === 'douyin' ? 'active' : '']"
                @click="publishForm.publishType = 'douyin'"
            >
              抖音发布
            </button>
<!--            <button
                :class="['type-btn', publishForm.publishType === 'xiaohongshu' ? 'active' : '']"
                @click="publishForm.publishType = 'xiaohongshu'"
            >
              小红书发布
            </button>-->
          </div>
        </div>

        <!-- 活动名称 -->
        <div class="form-section">
          <div class="section-label">活动名称</div>
          <el-input
              v-model="publishForm.activityName"
              placeholder="请输入活动名称"
              class="form-input"
          />
        </div>

        <!-- 标题 -->
        <div class="form-section">
          <div class="section-label">标题</div>
          <el-input
              v-model="publishForm.title"
              type="textarea"
              :rows="2"
              placeholder="发布时标题会自动携带(数字人请手动录入)"
              class="form-input"
          />

        </div>

        <!-- 话题 -->
        <div class="form-section">
          <div class="section-label">话题</div>
          <el-input-tag
              v-model="publishForm.topic"
              placeholder="请输入话题，按回车添加"
              class="form-input"
          />
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            一行代表一个话题
          </div>
        </div>

        <!-- 挂载 -->
        <div class="form-section" v-if="publishForm.publishType === 'douyin'">
          <div class="section-label">挂载</div>
          <div class="mount-buttons">
            <button
                :class="['mount-btn', publishForm.mount === 'none' ? 'active' : '']"
                @click="publishForm.mount = 'none'"
            >
              无
            </button>
            <button
                :class="['mount-btn', publishForm.mount === 'poi' ? 'active' : '']"
                @click="publishForm.mount = 'poi'"
            >
              POI地址/团购
            </button>
            <button
                :class="['mount-btn', publishForm.mount === 'miniprogram' ? 'active' : '']"
                @click="publishForm.mount = 'miniprogram'"
            >
              小程序
            </button>
          </div>
        </div>
        <!-- POI -->
        <div class="form-section" v-if="publishForm.publishType === 'douyin' && publishForm.mount === 'poi'">
          <div class="section-label">挂载内容</div>
          <div style="display: flex; gap: 8px; width: 100%;">
            <el-input v-model="publishForm.poi1" placeholder="请输入关键词" style="flex:1;" />
            <el-input v-model="publishForm.poi2" placeholder="请输入城市" style="flex:1;" />
            <el-button icon="el-icon-search" type="primary" @click="handleChooseCityKeyWord">搜索</el-button>
          </div>
          <div style="margin-top: 8px;">
            <el-select v-model="publishForm.poiSelect" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in cityData" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <!-- 小程序 -->
        <div class="form-section" v-if="publishForm.publishType === 'douyin' && publishForm.mount === 'miniprogram'">
          <div class="section-label">挂载内容</div>
          <el-input v-model="publishForm.miniId" placeholder="例如：ttef91b112671b152ba ID" style="margin-bottom: 8px;" />
          <el-input v-model="publishForm.miniTitle" placeholder="请输入小程序标题" style="margin-bottom: 8px;" />
          <el-input v-model="publishForm.miniPath" placeholder="例如：path/pages/index" />
        </div>
        <!-- 数据获取 -->
        <!-- <div class="form-section" v-if="publishForm.publishType === 'douyin'">
          <div class="section-label">数据获取</div>
          <div class="data-acquisition-row">
            <el-switch
                v-model="publishForm.dataAcquisition"
                active-color="#409EFF"
            />
            <div class="form-tip">
              <el-icon><InfoFilled /></el-icon>
              打开数据获取后,需要用户确定授权
            </div>
          </div>
        </div> -->

        <!-- 随机图片数量 -->
        <div class="form-section">
          <div class="section-label">随机图片数量</div>
          <el-input-number
              v-model="publishForm.picnums"
              :min="0"
              :max="9999"
              class="scan-limit-input"
          />
        </div>

        <!-- 扫码数量限制 -->
        <div class="form-section">
          <div class="section-label">扫码数量限制</div>
          <el-input-number
              v-model="publishForm.scanCodeLimit"
              :min="0"
              :max="9999"
              class="scan-limit-input"
          />
        </div>
      </div>
    </MyDialog>
    <MyDialog
        v-model="showQrCodeDialog"
        title="请扫码发布"
        width="600px"
        :modal="true"
        :close-on-click-modal="false"
        @confirm="handleQrCodeConfirm"
        @cancel="handleQrCodeConfirm"
    >
      <!-- 二维码显示区域 -->
      <div class="form-section" v-if="douyinQrCode || redBookAndroidQrCode || redBookIOSQrCode">
        <div class="qr-code-container">
          <!-- 抖音二维码 -->
          <div v-if="douyinQrCode" class="qr-code-item">
            <div class="qr-code-title">抖音二维码</div>
            <img :src="douyinQrCode" alt="抖音二维码" class="qr-code-image" />
          </div>
          <!-- 小红书Android二维码 -->
          <div v-if="redBookAndroidQrCode" class="qr-code-item">
            <div class="qr-code-title">小红书Android二维码</div>
            <img :src="redBookAndroidQrCode" alt="小红书Android二维码" class="qr-code-image" />
          </div>
          <!-- 小红书iOS二维码 -->
          <div v-if="redBookIOSQrCode" class="qr-code-item">
            <div class="qr-code-title">小红书iOS二维码</div>
            <img :src="redBookIOSQrCode" alt="小红书iOS二维码" class="qr-code-image" />
          </div>
        </div>
      </div>
    </MyDialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, computed} from 'vue'
import axiosUtil from '../../axios-util/axios-util'
import {VideoCamera, UploadFilled, InfoFilled} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {ElMessage, ElLoading} from 'element-plus'
import MyDialog from '../common/MyDialog.vue'
import SourcePictureNew from '../videoWarehouse/SourcePictureNew.vue'
import DouyinShow from './DouyinShow.vue';
import MyHeader from '../common/MyHeader.vue';
import utils from '../../utils/utils'
import QRCode from 'qrcode'

const router = useRouter()

//主题控制light  dark
const theme = utils.getTheme();
// 网站背景图
const website_bg_url = ref('')
// 网站logo
const website_logo = ref('')

const pictureContents = ref([])

interface SubMenuItem {
  id: number
  pid: number
  name: string
  url: string
  code: string
}

interface MenuItem {
  id: number
  pid: number
  name: string
  children?: SubMenuItem[]
  isOpen?: boolean
}

const menuList = ref<MenuItem[]>([
  {
    id:1,
    pid:0,
    name:'文生图Pro',
    children:[
      {
        id:11,
        pid:1,
        name:'文生图',
        url: "api/huoshan_open/text2_image/create_t2itask",
        code: "auto"
      }
    ]
  },{
    id:2,
    pid:0,
    name:'图生图Pro',
    children:[
      {
        id:21,
        pid:2,
        name:'图生图',
        url: "api/huoshan_open/text2_image/create_i2itask",
        code: null
      }
    ]
  }
])

const selectedSubMenu = ref<number | null>(null)
const description = ref('')
const count = ref(1)

const showDescriptionSection = computed(() => {
  // 21, 51 不显示描述，其余都显示，31-35要同时显示
  const uploadIds = [ 51, 31, 32, 33, 34, 35]
  return selectedSubMenu.value && !uploadIds.includes(selectedSubMenu.value) || [31,32,33,34,35].includes(selectedSubMenu.value)
})
const showUploadSection = computed(() => {
  const uploadIds = [21, 51, 31, 32, 33, 34, 35, 41,42,43,44,45,46,47,48,49,410]
  return selectedSubMenu.value && uploadIds.includes(selectedSubMenu.value)
})

// 获取当前选中的二级菜单对象
const currentSubMenu = computed(() => {
  for (const menu of menuList.value) {
    if (menu.children) {
      const found = menu.children.find(sub => sub.id === selectedSubMenu.value)
      if (found) return found
    }
  }
  return null
})

const toggleSubMenu = (menu: MenuItem) => {
  // 关闭其他所有菜单
  menuList.value.forEach(item => {
    if (item.id !== menu.id) {
      item.isOpen = false
    }
  })
  // 切换当前菜单
  menu.isOpen = !menu.isOpen
}

const selectSubMenu = (subMenu: SubMenuItem) => {
  selectedSubMenu.value = subMenu.id
  // 清空相关变量
  selectedImageData.value = null
  description.value = ''
  count.value = 1
  pictureContents.value = []
  taskNameInput.value = ''
}

const handleProductLibrary = () => {
  router.push('/videoWarehouse?id=12')
}

const handleGenerate = () => {
  // 判断描述和图片必填
  if (showDescriptionSection.value && !description.value) {
    ElMessage.error('请输入描述')
    return
  }
  if (showUploadSection.value && !selectedImageData.value) {
    ElMessage.error('请选择图片')
    return
  }

  // 清空之前的生成结果
  pictureContents.value = []

  // 弹出任务名输入框
  showTaskNameDialog.value = true;
}

const handlePublish = () => {
  console.log('点击授权发布按钮')
  showPublishDialog.value = true
}

const showUploadDialog = ref(false)
const sourcePictureNewRef = ref()
const selectedImageData = ref(null)

const handleCustomUploadClick = () => {
  showUploadDialog.value = true
}

function handleUploadConfirm() {
  if (sourcePictureNewRef.value && sourcePictureNewRef.value.getSelectMateria) {
    selectedImageData.value = sourcePictureNewRef.value.getSelectMateria();
  }
  showUploadDialog.value = false;
  // 清空任务名输入，因为上传了新图片
  taskNameInput.value = ''
}

// 任务名输入弹窗相关
const showTaskNameDialog = ref(false)
const taskNameInput = ref('')

// 发布设置弹窗相关
const showPublishDialog = ref(false)
const publishForm = ref({
  publishType: 'douyin', // douyin 或 xiaohongshu
  activityName: '',
  title: '',
  topic: [], // Changed to array for InputTag
  mount: 'none', // none, poi, miniprogram
  dataAcquisition: false,
  scanCodeLimit: 0,
  picnums: 0,
  // POI相关字段
  poi1: '',
  poi2: '',
  poiSelect: '',
  // 小程序相关字段
  miniId: '',
  miniTitle: '',
  miniPath: ''
})

const cityData = ref([])
const size = ref("1K")
const sizeArr = ref([{
  "code":"1K","name":"1K"
},{
  "code":"2K","name":"2K"
},{
  "code":"4K","name":"4K"
}])
const handleTaskNameCancel = () => {
  showTaskNameDialog.value = false
  taskNameInput.value = ''
  // 清空相关变量
  selectedImageData.value = null
  description.value = ''
  count.value = 1
  pictureContents.value = []
}

const handleTaskNameConfirm = () => {
  if (!taskNameInput.value.trim()) {
    ElMessage.error('请输入任务名')
    return
  }
  showTaskNameDialog.value = false
  // 这里继续后续生成逻辑，任务名为 taskNameInput.value
  // TODO: 用户自定义逻辑
  let params= {}
  let url = ''
  if(currentSubMenu.value.url === 'api/huoshan_open/text2_image/create_t2itask') {
    params = {
      prompt: description.value,
      // create_style: currentSubMenu.value.code,
      create_num: count.value,
      size: size.value,
      title: taskNameInput.value
    }
    url = currentSubMenu.value.url
  }
  if(currentSubMenu.value.url === 'api/huoshan_open/text2_image/create_i2itask') {
    params = {
      prompt: description.value,
      create_num: count.value,
      title: taskNameInput.value,
      image: selectedImageData.value,
      size: size.value,
    }
    url = currentSubMenu.value.url
  }
  if(currentSubMenu.value.url === 'create_graffiti_painting_task') {
    params = {
      base_image_url: selectedImageData.value[0],
      create_style: currentSubMenu.value.code,
      title: taskNameInput.value,
      create_num: count.value,
      prompt: description.value
    }
  }
  if(currentSubMenu.value.url === 'create_portrait_style_repainting_task') {
    params = {
      base_image_url: selectedImageData.value[0],
      style_index: currentSubMenu.value.code,
      create_num: count.value,
      title: taskNameInput.value
    }
  }
  if(currentSubMenu.value.url === 'create_super_resolution_image_task') {
    params = {
      title: taskNameInput.value,
      base_image_url: selectedImageData.value[0],
      scale: count.value
    }
  }

  // loading文本数组
  let loadingTexts = [
    '内容读取中',
    '素材提取中',
    '专场滤镜匹配中',
    'AI生成中',
    '预计一两分钟',
    '卡点特效匹配中'
  ];
  let loadingIndex = 0;
  let loadingInstance = ElLoading.service({
    lock: true,
    text: loadingTexts[0],
    background: 'rgba(0, 0, 0, 0.7)'
  });
  let loadingTextTimer = setInterval(() => {
    loadingIndex = (loadingIndex + 1) % loadingTexts.length;
    if (loadingInstance) loadingInstance.setText(loadingTexts[loadingIndex]);
  }, 1200);

  axiosUtil.post(url,params).then(response => {
    if (response.data.code === 1) {
      const id = response.data.data.id;
      let timer = setInterval(() => {
        axiosUtil.post('api/aliyun_tongyi/wan_xiang/query_image_task', {
          id: id
        }).then(responseSon => {
          if(responseSon.data.code===1 && responseSon.data.data.list && responseSon.data.data.list.length > 0) {
            let list = responseSon.data.data.list;
            list.map(picData => {
              const picShow = {
                id: picData.id,
                bg: picData.url,
                avatar: 'https://img2.baidu.com/it/u=2328777830,2201725034&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                likes: 9999,
                comments: 9999,
                favorites: 9999,
                shares: 9999,
                author: '@智慧AI测试',
                desc: "",
                url: picData.url
              }
              pictureContents.value.push(picShow)
            })
            clearInterval(timer);
            clearInterval(loadingTextTimer);
            if (loadingInstance) loadingInstance.close();
            ElMessage.success('生成图片成功');
          }
        })
      },5000)
    }else {
      clearInterval(loadingTextTimer);
      if (loadingInstance) loadingInstance.close();
      ElMessage.error('生成图片出错');
    }
  }).catch(() => {
    clearInterval(loadingTextTimer);
    if (loadingInstance) loadingInstance.close();
    ElMessage.error('生成图片出错');
  })

  // 清空任务名输入
  taskNameInput.value = ''
}

const showQrCodeDialog = ref(false)
const handleQrCodeConfirm = () =>{
  // 清空发布表单
  publishForm.value = {
    publishType: 'douyin',
    activityName: '',
    title: '',
    topic: [], // Reset to empty array for InputTag
    mount: 'none',
    dataAcquisition: true,
    scanCodeLimit: 0,
    picnums: 0,
    // POI相关字段
    poi1: '',
    poi2: '',
    poiSelect: '',
    // 小程序相关字段
    miniId: '',
    miniTitle: '',
    miniPath: ''
  }
  // 清空二维码
  douyinQrCode.value = ""
  redBookAndroidQrCode.value = ""
  redBookIOSQrCode.value = ""
  // 清空城市数据
  cityData.value = []
  showQrCodeDialog.value = false;
}

// 发布设置弹窗处理方法
const handlePublishConfirm = async () => {
  console.log('发布设置确认', publishForm.value)
  let photos = ''
  let arr = []
  if(pictureContents.value.length > 0) {
    pictureContents.value.forEach(pic => {
      arr.push(pic.url)
    })
  }else {
    ElMessage.warning('请先生成图片')
  }
  photos = arr.join(",")
  // TODO: 在这里处理发布逻辑
  let url = ''
  let data: any = {
    "title": publishForm.value.activityName,
    "video_text": publishForm.value.title,
    "video_text_keyword": publishForm.value.topic,
    "platform_type": "none",
    "micro_app_info": {
      "micro_app_id": "",
      "micro_app_title": "",
      "micro_app_url": ""
    },
    "open_data": publishForm.value.dataAcquisition?1:0,
    "video_list": "",
    "max_release_num": publishForm.value.scanCodeLimit,
    "type": "images",
    "photos": photos,
    "photos_num": publishForm.value.picnums,
    "id": ""
  }

  if(publishForm.value.publishType === 'douyin'){
    url = 'api/scan_publish/douyin/save';
    // 处理POI挂载
    if(publishForm.value.mount === 'poi'){
      if(!publishForm.value.poiSelect){
        ElMessage.warning("请先选择数据")
        return
      }else {
        const selectArr = cityData.value.find(item => item.value === publishForm.value.poiSelect)
        if(selectArr){
          data.mount_type = 'poi'
          data.poi_id = selectArr.value
          data.poi_name = selectArr.label
        }
      }
    }

    // 处理小程序挂载
    if(publishForm.value.mount === 'miniprogram'){
      if(!publishForm.value.miniId){
        ElMessage.warning("请先输入小程序ID")
        return
      }
      if(!publishForm.value.miniTitle){
        ElMessage.warning("请先输入标题")
        return
      }
      if(!publishForm.value.miniPath){
        ElMessage.warning("请先输入路径")
        return
      }
      data.mount_type = 'mini_program'
      data.micro_app_info.micro_app_id = publishForm.value.miniId
      data.micro_app_info.micro_app_title = publishForm.value.miniTitle
      data.micro_app_info.micro_app_url = publishForm.value.miniPath
    }
  }else {
    url = 'api/scan_publish/xhs/save'
  }
  const response = await axiosUtil.post(url, data)
  if(response.data.code === 1) {
    ElMessage.success(response.data.msg)
    const qr_code = response.data.data.qr_code
    if(publishForm.value.publishType === 'douyin'){
      // 将地址转换为二维码图片
      douyinQrCode.value = await generateQRCode(qr_code)
    }else {
      // 将地址转换为二维码图片
      redBookAndroidQrCode.value = await generateQRCode(qr_code.android)
      redBookIOSQrCode.value = await generateQRCode(qr_code.ios)
    }
    showQrCodeDialog.value = true
    showPublishDialog.value = false
  }else {
    ElMessage.error(response.data.msg)
  }
}

const douyinQrCode = ref("")
const redBookAndroidQrCode = ref("")
const redBookIOSQrCode = ref("")

// 生成二维码的函数
const generateQRCode = async (text: string): Promise<string> => {
  try {
    const qrCodeDataUrl = await QRCode.toDataURL(text, {
      width: 200,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
    return qrCodeDataUrl
  } catch (error) {
    console.error('生成二维码失败:', error)
    return ''
  }
}

const handlePublishCancel = () => {
  showPublishDialog.value = false
  // 重置表单
  publishForm.value = {
    publishType: 'douyin',
    activityName: '',
    title: '',
    topic: [], // Reset to empty array for InputTag
    mount: 'none',
    dataAcquisition: true,
    scanCodeLimit: 0,
    picnums: 0,
    // POI相关字段
    poi1: '',
    poi2: '',
    poiSelect: '',
    // 小程序相关字段
    miniId: '',
    miniTitle: '',
    miniPath: ''
  }
  // 清空城市数据
  cityData.value = []
}

const handleChooseCityKeyWord = async () => {
  if(!publishForm.value.poi1){
    ElMessage.warning("请输入关键词")
    return
  }
  if(!publishForm.value.poi2){
    ElMessage.warning("请输入城市")
    return
  }
  const res = await axiosUtil.post('api/scan_publish/douyin/search_poi', {
    "keyword": publishForm.value.poi1,
    "city": publishForm.value.poi2
  })
  if(res.data.code){
    cityData.value = []
    res.data.code.forEach(item=>{
      const son = {
        value: item.poi_id,
        label: item.province  + item.city + item.district + item.address,
      }
      cityData.value.push(son)
    })
  }
}

const handleReset = () => {
  // 清空所有相关变量
  selectedSubMenu.value = null
  selectedImageData.value = null
  description.value = ''
  count.value = 1
  pictureContents.value = []
  taskNameInput.value = ''
  showUploadDialog.value = false
  showTaskNameDialog.value = false
  showPublishDialog.value = false
  showQrCodeDialog.value = false
  cityData.value = []
  douyinQrCode.value = ""
  redBookAndroidQrCode.value = ""
  redBookIOSQrCode.value = ""

  // 重置发布表单
  publishForm.value = {
    publishType: 'douyin',
    activityName: '',
    title: '',
    topic: [],
    mount: 'none',
    dataAcquisition: true,
    scanCodeLimit: 0,
    picnums: 0,
    poi1: '',
    poi2: '',
    poiSelect: '',
    miniId: '',
    miniTitle: '',
    miniPath: ''
  }

  // 关闭所有菜单
  menuList.value.forEach(menu => {
    menu.isOpen = false
  })

  ElMessage.success('已重置所有数据')
}

// 添加页面初始化时的清空逻辑
onMounted(() => {
  initWebsiteBgUrl()
  document.body.classList.remove('login-page')
  // 初始化时清空相关变量
  selectedSubMenu.value = null
  selectedImageData.value = null
  description.value = ''
  count.value = 1
  pictureContents.value = []
  taskNameInput.value = ''
  showUploadDialog.value = false
  showTaskNameDialog.value = false
  showPublishDialog.value = false
  showQrCodeDialog.value = false
  cityData.value = []
  douyinQrCode.value = ""
  redBookAndroidQrCode.value = ""
  redBookIOSQrCode.value = ""
})

//读取配置，获取网站背景图和网站logo
const initWebsiteBgUrl = async () => {
  const response = await axiosUtil.post('api/pc/site/get_agent_config', {})
  if (response.data.code === 0 && response.data.data) {
    website_bg_url.value = import.meta.env.VITE_APP_SERVER + response.data.data.website_bg || ''
    website_logo.value = import.meta.env.VITE_APP_SERVER + response.data.data.website_logo || ''
  }
}
</script>

<style scoped>
.son-page-container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.main-container {
  height: 100vh;
  width: 100%;
  backdrop-filter: blur(5px);
}

.header-container {
  padding: 0;
  width: 100%;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  backdrop-filter: blur(10px);
  border-bottom: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  box-shadow: 0 4px 6px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 0, 0, 0.1)"');
}

.son-frame-nav-title {
  padding: 20px 40px;
  color: #fff;
  font-size: 1.4rem;
  font-weight: bold;
  text-shadow: 0 2px 8px #003366, 0 0 16px #00aaff;
  letter-spacing: 6px;
}

.el-main {
  padding: 20px;
  height: 85vh;
  overflow-x: hidden;
}

.el-row {
  height: 100%;
  margin: 0 !important;
}

.el-col {
  height: 100%;
}

.area-container {
  height: 100%;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  box-shadow: 0 4px 6px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.1)" : "rgba(0, 0, 0, 0.1)"');
  transition: all 0.3s ease;
  padding: 15px;
}

.area-container:hover {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.15)" : "rgba(255, 255, 255, 0.15)"');
  box-shadow: 0 6px 12px v-bind('theme === "light" ? "rgba(0, 0, 0, 0.15)" : "rgba(0, 0, 0, 0.15)"');
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
}

.menu-container {
  overflow-y: auto;
}
.area-container-sec {
  height: calc(100% - 80px) !important;
}

.center-area, .right-area {
  min-height: 70vh;
}

.menu-container::-webkit-scrollbar {
  width: 6px;
}

.menu-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.menu-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.menu-item {
  margin-bottom: 15px;
}

.menu-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  border-radius: 4px;
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  cursor: pointer;
  transition: all 0.3s ease;
}

.menu-title:hover {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.15)" : "rgba(255, 255, 255, 0.15)"');
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
}

.arrow {
  width: 0;
  height: 0;
  border-style: solid;
  transition: all 0.3s ease;
}

.arrow-right {
  border-width: 6px 0 6px 8px;
  border-color: transparent transparent transparent #fff;
}

.arrow-down {
  border-width: 8px 6px 0 6px;
  border-color: #fff transparent transparent transparent;
}

.sub-menu {
  margin-top: 5px;
  margin-left: 15px;
}

.sub-menu-item {
  padding: 10px 15px;
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  margin-bottom: 5px;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
}

.sub-menu-item:hover {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.15)" : "rgba(255, 255, 255, 0.15)"');
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
}

.sub-menu-item.active {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.4)" : "rgba(255, 255, 255, 0.4)"');
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
}

.center-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 20px;
}

.center-top {
  flex: 2;
  min-height: 0;
  max-height: 100%;
  overflow-y: auto;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 4px;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  padding: 15px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.center-top::-webkit-scrollbar {
  width: 8px;
  background: transparent;
}
.center-top::-webkit-scrollbar-thumb {
  background: v-bind('theme === "light" ? "rgba(0,204,255,0.25)" : "rgba(0,204,255,0.25)"');
  border-radius: 6px;
  transition: background 0.3s;
}
.center-top::-webkit-scrollbar-thumb:hover {
  background: v-bind('theme === "light" ? "rgba(0,204,255,0.45)" : "rgba(0,204,255,0.45)"');
}
.center-top::-webkit-scrollbar-track {
  background: v-bind('theme === "light" ? "rgba(255,255,255,0.08)" : "rgba(255,255,255,0.08)"');
  border-radius: 6px;
}

.center-bottom {
  flex: 1;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 4px;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  padding: 15px;
  box-sizing: border-box;
}

.input-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.section-title {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 500;
}

.description-input {
  flex: 1;
  min-height: 0;
  width: 100%;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
  border-radius: 4px;
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  padding: 10px;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}

.description-input:focus {
  outline: none;
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.6)" : "rgba(255, 255, 255, 0.6)"');
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
}

.description-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.count-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.section-content {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 4px;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  padding: 15px;
}

.generate-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.generate-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.generate-row:last-child {
  margin-bottom: 0;
  justify-content: flex-start;
}

.button-row {
  justify-content: center !important;
}

.row-label {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  font-size: 14px;
  font-weight: 500;
  min-width: 60px;
}

.count-input {
  width: 120px;
}

.size-select {
  width: 120px;
}

.size-select :deep(.el-input__wrapper) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  box-shadow: 0 0 0 1px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
}

.size-select :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.5)" : "rgba(255, 255, 255, 0.5)"');
}

.size-select :deep(.el-input__inner) {
  color: #fff;
}

.size-select :deep(.el-input__suffix) {
  color: #fff;
}

.size-select :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

.size-select :deep(.el-select__selected-item) {
  color: #fff;
}

.size-select :deep(.el-select__placeholder) {
  color: rgba(255, 255, 255, 0.5);
}

.count-input :deep(.el-input-number__decrease),
.count-input :deep(.el-input-number__increase) {
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.4)" : "rgba(0, 102, 204, 0.4)"');
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.3)" : "rgba(0, 204, 255, 0.3)"');
  color: #fff;
}

.count-input :deep(.el-input-number__decrease:hover),
.count-input :deep(.el-input-number__increase:hover) {
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.6)" : "rgba(0, 102, 204, 0.6)"');
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.5)" : "rgba(0, 204, 255, 0.5)"');
}

.count-input :deep(.el-input__wrapper) {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  box-shadow: 0 0 0 1px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
}

.count-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.5)" : "rgba(255, 255, 255, 0.5)"');
}

.count-input :deep(.el-input__inner) {
  color: #fff;
}

.generate-btn {
  width: 120px;
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.6)" : "rgba(0, 102, 204, 0.6)"') !important;
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.4)" : "rgba(0, 204, 255, 0.4)"') !important;
  color: #fff !important;
  transition: all 0.3s ease;
  margin-left: 0;
}

.generate-btn:hover {
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.8)" : "rgba(0, 102, 204, 0.8)"') !important;
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.6)" : "rgba(0, 204, 255, 0.6)"') !important;
  box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(0, 204, 255, 0.3)" : "rgba(0, 204, 255, 0.3)"');
}

.upload-section {
  margin-top: 15px;
}

.upload-component {
  width: 100%;
}

.upload-component :deep(.el-upload) {
  width: 100%;
}

.upload-component :deep(.el-upload-dragger) {
  width: 100%;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border: 1px dashed v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
  border-radius: 4px;
}

.upload-component :deep(.el-upload-dragger:hover) {
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.6)" : "rgba(255, 255, 255)"');
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.15)" : "rgba(255, 255, 255, 0.15)"');
}

.upload-component :deep(.el-icon--upload) {
  margin: 20px 0 16px;
  font-size: 48px;
  color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.6)" : "rgba(0, 204, 255, 0.6)"');
}

.upload-component :deep(.el-upload__text) {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(0, 0, 0, 0.8)"');
  font-size: 14px;
  text-align: center;
  margin: 0 0 16px;
}

.upload-component :deep(.el-upload__text em) {
  color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.8)" : "rgba(0, 204, 255)"');
  font-style: normal;
}

.upload-component :deep(.el-upload__tip) {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "rgba(255, 255, 255)"');
  font-size: 12px;
  text-align: center;
}

.right-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-header {
  height: 10%;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 5px;
}

.header-title {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255)"');
  font-size: 20px;
  font-weight: bold;
}

.header-subtitle {
  color: v-bind('theme === "light" ? "rgba(0, 0, 0, 0.6)" : "rgba(255, 255, 255)"');
  font-size: 12px;
}

.right-main {
  height: 80%;
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border-radius: 4px;
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  margin: 10px 0;
}

.right-footer {
  height: 10%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.publish-btn {
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.6)" : "rgba(0, 102, 204, 0.6)"') !important;
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.4)" : "rgba(0, 204, 255, 0.4)"') !important;
  color: #fff !important;
  transition: all 0.3s ease;
}

.publish-btn:hover {
  background: v-bind('theme === "light" ? "rgba(0, 102, 204, 0.8)" : "rgba(0, 102, 204, 0.8)"') !important;
  border-color: v-bind('theme === "light" ? "rgba(0, 204, 255, 0.6)" : "rgba(0, 204, 255, 0.6)"') !important;
  box-shadow: 0 0 15px v-bind('theme === "light" ? "rgba(0, 204, 255, 0.3)" : "rgba(0, 204, 255, 0.3)"');
}

.spacer {
  height: 80px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  /* padding: 0 20px; */
  /* margin-top: 3vh; */
}

.content-nav {
  height: 100%;
  width: 100%;
  display: flex;
  /* justify-content: flex-end; */
  align-items: center;
  /* padding: 0 20px; */
  background: transparent;
  border: none;
  box-shadow: none;
}

.nav-right {
  display: flex;
  align-items: start;
  width: 100%;
  height: 100%;
  padding-bottom: 12px;
}

.nav-btn {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.1)" : "rgba(255, 255, 255, 0.1)"');
  border: 1px solid v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  color: #fff;
  padding: 12px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
  height: 100%;
}

.nav-btn:hover {
  background: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
  border-color: v-bind('theme === "light" ? "rgba(255, 255, 255, 0.3)" : "rgba(255, 255, 255, 0.3)"');
  box-shadow: 0 0 10px v-bind('theme === "light" ? "rgba(255, 255, 255, 0.2)" : "rgba(255, 255, 255, 0.2)"');
}

.btn-icon {
  font-size: 16px;
}

/* 发布设置弹窗样式 */
.publish-form {
  padding: 20px;
}

.form-section {
  margin-bottom: 24px;
}

.section-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.publish-type-buttons {
  display: flex;
  gap: 12px;
}

.type-btn {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.type-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.type-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.form-input {
  width: 100%;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.mount-buttons {
  display: flex;
  gap: 12px;
}

.mount-btn {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 12px;
}

.mount-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.mount-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.data-acquisition-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.scan-limit-input {
  width: 120px;
}

/* 二维码显示样式 */
.qr-code-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
}

.qr-code-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.qr-code-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.qr-code-image {
  width: 150px;
  height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>

<style>
/* 隐藏全局背景图 */
body::before {
  display: none !important;
}

/* 优化Son页面背景图和滚动条 */
html, body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}

body {
  background: url(../../assets/main/背景.png) no-repeat center center;
  background-size: cover;
}
</style>
